package com.cy.ppj.service.comm.impl;

import com.aliyun.oss.OSSClient;
import com.cy.ppj.comm.constant.Constants;
import com.cy.ppj.comm.properties.OssProperties;
import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.comm.utils.SpringContextUtils;
import com.cy.ppj.model.Result;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.comm.FileService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * @description: Oss文件管理
 * @author: Ocean
 * @create: 2018-07-30 16:18
 **/
@Slf4j
@Service
public class OssFileServiceImpl extends BaseService implements FileService {

    @Autowired
    private OSSClient ossClient;

    @Override
    public Result upload(MultipartFile file) {
        String ossFileName = null;
        boolean flag = false;
        try {
        	InputStream inputStream = file.getInputStream();
        	String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            ossFileName = UUID.randomUUID().toString().concat(suffix);
            log.info("OSS upload:[{}]-->[{}]", fileName, ossFileName);
            ossClient.putObject(Constants.FILE_PTAH, ossFileName, inputStream);
            flag = true;
        } catch (Exception e) {
            log.error("upload error:", e);
        }
        return flag ? Result.success("上传成功", ossFileName) : Result.fail("上传失败");
    }

	@Override
	public Result uploadToFullBucket(MultipartFile file) {
		String ossFileName = null;
        boolean flag = false;
        try {
        	InputStream inputStream = file.getInputStream();
        	String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            ossFileName = UUID.randomUUID().toString().concat(suffix);
            log.info("OSS upload:[{}]-->[{}]", fileName, ossFileName);
            ossClient.putObject(Constants.FULL_FILE_PTAH, ossFileName, inputStream);
            flag = true;
        } catch (Exception e) {
            log.error("upload error:", e);
        }
        return flag ? Result.success("上传成功", getFullAccessUrl(Constants.FULL_FILE_PTAH, SpringContextUtils.getBean(OssProperties.class).getEndpoint(), ossFileName)) : Result.fail("上传失败");
	}

    @Override
    public Result<Map<String, String>> uploadToMallBucket(MultipartFile multipartFile, String directory, String fileName) {

        long fileLength = multipartFile.getSize();
        if(fileLength > Constants.MAX_FILE_SIZE.longValue()) {
            return Result.fail("图片大小不可超过" + Constants.MAX_FILE_SIZE_MB + "MB");
        }

        boolean flag = false;
        String key = "";
        String bucketName = Constants.MALL_BUCKET_NAME;
        try {

            InputStream inputStream = multipartFile.getInputStream();
            String originalFileName = multipartFile.getOriginalFilename();
            String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
            if(CommonUtils.isEmpty(fileName)) {
                //如果文件名为空，则生成一个唯一的文件名
                fileName = UUID.randomUUID().toString();
            }
            key = directory.concat(fileName).concat(suffix);
            log.info("OSS 上传图片 uploadImage:[{}]-->[{}]", fileName, key);
            log.info("图片大小为：{} ", fileLength/(1024 * 1024) == 0 ? fileLength/1024 + "Kb" : fileLength/(1024 * 1024) + "Mb");
            //上传
            ossClient.putObject(bucketName, key, inputStream);
            flag = true;

        } catch (Exception e) {
            log.error("uploadToMallBucket error 上传文件到 MALL_BUCKET_NAME 异常", e);
        }

        if(!flag) {
            return Result.fail("上传失败");
        }

        Map<String, String> map = new HashMap<>();
        map.put("path", key);
        map.put("src", getFileUrl(key, bucketName));

        return Result.success("上传成功", map);
    }

    private String getFullAccessUrl(String fullBucketName, String endpoint, String ossFileName) {
		return "https://".concat(fullBucketName).concat(".").concat(endpoint).concat("/").concat(ossFileName);
	}

	@Override
	public String getFileUrl(String key, String bucketName) {
		
		Date expiration = CommonUtils.addTime(new Date(), 2, Calendar.HOUR_OF_DAY);
		URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
		
		return url.toString();
	}
}
